package com.alex.core.mq;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.ddcx.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author xc
 * @date 2018/6/16
 */

public class RocketMQProducer extends ProducerBean {


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String topic;

    public RocketMQProducer(String mqTopic) {
        this.topic = mqTopic;
    }

    public void sendMsg(String content,String tag, String keyId, int second) throws CustomException {
        Message msg = new Message(topic, tag, content.getBytes());
        if (keyId != null) {
            msg.setKey(keyId);
        }
        try {
            SendResult sendResult = this.send(msg);
            assert sendResult != null;
            logger.debug("消息发送成功:keyId：{},msgId:{} ,topic{},tag{},content{}", keyId, sendResult.getMessageId(), topic,tag, content);
        } catch (ONSClientException e) {
            logger.error("消息发送失败:keyId：{},topic{},tag{},异常{}", keyId, topic,tag,e);
            throw new CustomException(500,"消息发送失败",e.getMessage());
        }
    }

    public void sendSecondMsg(String content, String tag, String type, String keyId, int second) throws CustomException {
        Message msg = new Message(topic, type, content.getBytes());
        if (keyId != null) {
            msg.setKey(keyId);
        }
        try {
            if (second != 0) {//定时
                msg.setStartDeliverTime(System.currentTimeMillis() + second * 1000);
            }
            SendResult sendResult = this.send(msg);
            assert sendResult != null;
            logger.debug("消息发送成功:keyId：{},type:{}, msgId:{} ,topic:{}", keyId, type, sendResult.getMessageId(), topic);
        } catch (ONSClientException e) {
            logger.error("消息发送失败:keyId：{},topic{},tag{},异常{}", keyId, topic,tag,e);
            throw new CustomException(500,"消息发送失败",e.getMessage());
        }
    }
}
